import {writeFile} from 'fs/promises'
import {join} from 'path'
import {getUserFromSession} from "@/lib/auth";
import Link from "next/link";
import {redirect} from "next/navigation";
import {useIsClient} from "@/lib/hooks";

export default async function ServerUploadPage() {
    const user = await getUserFromSession()

    async function upload(data: FormData) {
        'use server'

        const file: File | null = data.get('file') as unknown as File
        if (!file) {
            throw new Error('No file uploaded')
        }
        // video/* audio/* image/*
        if (file.type !== 'video/mp4') {
            throw new Error('The file type is not support')
        }

        const bytes = await file.arrayBuffer()
        const buffer = Buffer.from(bytes)

        // 这里是你要进行保存的文件目录地址
        const path = join('./', 'public/videos', file.name)
        await writeFile(path, buffer)
        console.log(`open ${path} to see the uploaded file`)

        redirect('/')
        // return {success: true}
    }

    return (
        <main className={'flex flex-col gap-2 items-center'}>
                {user ? <> <h1 className={'font-bold text-xl'}>Upload Your Video</h1>
                <form action={upload} className={'flex flex-col items-center gap-2'}>
                    <input type="file" name="file"/>
                    <input
                        className={'disabled:bg-slate-500 hover:bg-green-300 bg-green-200 rounded w-28 py-1'}
                        type="submit" value="Upload"/>
                </form>
            </> : <div className={'flex flex-row items-center'}>
                <Link className={'text-blue-300'}
                      href={'/signin'}>Please Login</Link>
            </div>}
        </main>
    )
}